<template>
  <view class="search-result-container">
     <!-- 导航栏 -->
  <view class="nav">
    <scroll-view :scroll-left="scrollLeft" scroll-with-animation :scroll-into-view="isActive" scroll-x="true">
      <view class="tab-list">
        <view @click="toggle(item.id,index)" :id="item.id" :class="{'active':isActive===item.id}" class="tab-item"
          v-for="item,index in tabs" :key="item.id">
          {{item.name}}
        </view>
        <view class="line-box" :style="{'width':lineCurrentAttr.width+'px','left':lineCurrentAttr.left+'px'}">
        </view>
      </view>
    </scroll-view>
  </view>
  <!-- 轮播内容 -->
  <swiper v-if="scrollH" :style="{'height':scrollH}" :current="currentIndex" @animationfinish="pageToggle" :interval="3000"
    :duration="1000">
    <swiper-item>
      <!-- 单曲 -->
      <scroll-view @scrolltolower="dataLoad" :style="{'height':scrollH}" scroll-y="true">
        <song-list :status="status" :list="allDate[0].list"></song-list>
      </scroll-view>
    </swiper-item>
    <swiper-item>
      <!-- 歌单 -->
      <scroll-view @scrolltolower="dataLoad" :style="{'height':scrollH}" scroll-y="true">
        <song-order-list :key="tabs[1].query.keywords" :status="status" :list="allDate[1].list"></song-order-list>
      </scroll-view>
    </swiper-item>
    <swiper-item>
      <!-- 视频 -->
      <scroll-view @scrolltolower="dataLoad" :style="{'height':scrollH}" scroll-y="true">
        <video-list :status="status" :list="allDate[2].list"></video-list>
      </scroll-view>
    </swiper-item>
    <swiper-item>
      <!-- 歌手 -->
      <scroll-view @scrolltolower="dataLoad" :style="{'height':scrollH}" scroll-y="true">
        <singer-list :status="status" :list="allDate[3].list"></singer-list>
      </scroll-view>
    </swiper-item>
    <swiper-item>
      <!-- 专辑 -->
      <scroll-view  @scrolltolower="dataLoad" :style="{'height':scrollH}" scroll-y="true">
        <album-list :status="status" :list="allDate[4].list"></album-list>
      </scroll-view>
    </swiper-item>
  </swiper>
  </view>
 
</template>
<script setup>
  import {
    onLoad,
  } from "@dcloudio/uni-app"
  import {
    searchResult,
    getVideoUrl,getVideoDetail
  } from '@/request/api.js'
  import {
    computed,
    getCurrentInstance,
    onMounted,
    reactive,
    ref
  } from "vue";
  const tabs = [{
      name: '单曲',
      id: 'tab1',
      query: {
        keywords: '',
        type: 1,
        offset: 0,
        page:0
      }
    },
    {
      name: '歌单',
      id: 'tab2',
      query: {
        keywords: '',
        type: 1000,
        offset: 0,
        page:0
      }
    },
    {
      name: '视频',
      id: 'tab3',
      query: {
        keywords: '',
        type: 1014,
        offset: 0,
        page:0
      }
    },
    {
      name: '歌手',
      id: 'tab4',
      query: {
        keywords: '',
        type: 100,
        offset: 0,
        page:0
      }
    },
    {
      name: '专辑',
      id: 'tab5',
      query: {
        keywords: '',
        type: 10,
        offset: 0,
        page:0
      }
    }
  ]
  // 计算line属性
  const status = ref('more')
  const lineCurrentAttr = computed(() => {
    return tabs[currentIndex.value].slider === undefined ? {
      left: 0,
      width: 0
    } : tabs[currentIndex.value].slider
  })
  const _this = getCurrentInstance()

  const calLineAttr = () => {
    let query = uni.createSelectorQuery().in(_this)
    tabs.forEach((v, index) => {
      query.select(`#${v.id}`).boundingClientRect(res => {
        let width = res.width
        let left = res.left - uni.upx2px(20)
        v.slider = {
          width,
          left
        }
      }).exec()
    })
  }

  const scrollH = ref('')
  onMounted(() => {
    setTimeout(() => {
      calLineAttr()
    }, 0)
    setTimeout(() => {
      setScrollH()
    }, 500)
  })
  const setScrollH = () => {
    uni.getSystemInfo({
      success(resu) {
        const query = uni.createSelectorQuery()
        query.select('.nav').boundingClientRect()
        query.exec(res => {
          if (res[0].height !== 0) {
            scrollH.value = resu.windowHeight - res[0].height - uni.upx2px(60) + 'px'
            return
          } else {
            setScrollH()
          }
        })
      }
    })
  }
  const allDate = ref([{
      list: [],
      count: 0
    },
    {
      list: [],
      count: 0
    },
    {
      list: [],
      count: 0
    },
    {
      list: [],
      count: 0
    },
    {
      list: [],
      count: 0
    }
  ])
  onLoad(async (option) => {
    const key = option.keyWord
    tabs.forEach(v => {
      v.query.keywords = key
    })
    getSearchResult()
  })
  const currentIndex = ref(0)
  const getSearchResult = async () => {
    const res = await searchResult(tabs[currentIndex.value].query)
    if (currentIndex.value === 0) {
      allDate.value[currentIndex.value].list.push(...res.result.songs)
      allDate.value[currentIndex.value].count = res.result.songCount
    } else if (currentIndex.value === 1) {
      allDate.value[currentIndex.value].list.push(...res.result.playlists)
      allDate.value[currentIndex.value].count = res.result.playlistCount
    } else if (currentIndex.value === 2) {
      // 视频，循环获取视频地址   1AF42282920EE6DAE9142940A4BB28E7
      res.result.videos = res.result.videos.filter(v=>v.vid.length>16) // 筛选无效vid
      // console.log(res.result.videos);
      let list = []
      let list1 = []
      console.log(1,res.result.videos);
      res.result.videos.forEach((v) => {
        list.push(getVideoUrl(v.vid))
        list1.push(getVideoDetail(v.vid))
      })
      
      const results = await Promise.all(list)
      let results1 = await Promise.all(list1)
      results1 = results1.map((v,idx) => {
        v.data.videoUrl = results[idx].urls
        return v.data
      })
      results1 = results1.filter(v=>v.videoUrl.length)
      allDate.value[currentIndex.value].list.push(...results1)
      allDate.value[currentIndex.value].count = res.result.videoCount - (15-results1.length)
    } else if (currentIndex.value === 3) {
      allDate.value[currentIndex.value].list.push(...res.result.artists)
      allDate.value[currentIndex.value].count = res.result.artistCount
    } else {
      allDate.value[currentIndex.value].list.push(...res.result.albums)
      allDate.value[currentIndex.value].count = res.result.albumCount
    }
  }
  const isActive = ref('tab1')
  const scrollLeft = ref(0)
  // 切换tabs
  const toggle = (id, index) => {
    isActive.value = id
    currentIndex.value = index
    scrollLeft.value = index >= 3 ? index * 25 : 0
  }

  const pageToggle = async (e) => {
    const index = e.detail.current
    const num = index + 1
    const id = 'tab' + num
    toggle(id, index)
    // 动画结束后
    if (allDate.value[index].list.length === 0) {
      await getSearchResult()
      if (allDate.value[currentIndex.value].count <= 15 * (tabs[currentIndex.value].query.page + 1)) {
        // 没有更多数据
        status.value = 'no-more'
        return
      }
    }
  }

  const dataLoad = async () => {
    status.value = 'loading'
    if (allDate.value[currentIndex.value].count <= 15 * (tabs[currentIndex.value].query.page + 1)) {
      // 没有更多数据
      status.value = 'no-more'
      return
    }
    tabs[currentIndex.value].query.page++
    tabs[currentIndex.value].query.offset+=15
    await getSearchResult()
    status.value = 'more'
  }
</script>

<style lang="less">
  page{
    height: 100%;
  }
  .search-result-container{
      height: 100%;
      overflow: hidden;
  }
  .nav {
    margin: 40rpx 0 20rpx 0;

    scroll-view {
      // padding: 30rpx;
      // margin: 30rpx;
      white-space: nowrap;
      width: 100%;

      .tab-list {
        display: inline-flex;
        position: relative;

        .line-box {
          background-color: red;
          transition: 0.5s;
          height: 6rpx;
          position: absolute;
          bottom: 0;
          margin: 0 20rpx;
        }

        .tab-item {
          box-sizing: border-box;
          position: relative;
          // background-color: aqua;
          padding: 0 20rpx 20rpx 20rpx;
          margin: 0 20rpx;
          color: #666666;
          // &::before{
          //   content: '';
          //   position: absolute;
          //   bottom: 0;
          //   left: 0;
          //   width: 100%;
          //   height: 8rpx;
          //   border-radius: 4rpx;    
          //   transition: 0.5s;

          // }
          &.active {
            font-weight: bold;
            color: #000;
            // &::before{
            //   background-color: red;
            // }
          }
        }



      }
    }
  }


  swiper {
    padding: 15rpx;

    .more {
      display: flex;
      align-items: center;
    }
  }
</style>
